package com.ruoyi.bearing.service.Impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.ruoyi.bearing.domain.BearingDiagnosisResult;
import com.ruoyi.bearing.domain.BearingModel;
import com.ruoyi.bearing.service.IBearingDiagnosisService;
import com.ruoyi.bearing.service.IBearingSignalService;
import com.ruoyi.common.constant.FlaskDataConstants;
import com.ruoyi.common.constant.FlaskDiagnosisConstants;
import com.ruoyi.common.constant.FlaskModelConstants;
import com.ruoyi.common.enums.FilteringType;
import com.ruoyi.common.exception.flask.FlaskException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.flask.HttpFlask;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 在线诊断
 */
@Service
public class BearingDiagnosisServiceImpl implements IBearingDiagnosisService {
    /**
     * 在线诊断
     */
    public List<BearingDiagnosisResult> startBearingDiagnosis(MultipartFile file, BearingModel bearingModel) throws IOException, IllegalAccessException {
        List<BearingDiagnosisResult> bearingDiagnosisRes = new ArrayList<>();
        // 请求动态路径
        String res = HttpFlask.sendGetFlask(FlaskModelConstants.Model_CSV_URL);
        if (!"".equals(res)) {
            JSONObject jsonObject = JSONObject.parseObject(res);
            String dir = (String) jsonObject.get("data");
            String csvName = FileUploadUtils.upload(dir, file);
            String csvFileName = csvName.split("csv/")[1];
            bearingModel.setFileName(csvFileName);
            String postParam = HttpFlask.getKeyAndValueString(bearingModel);
            // 进行在线诊断
            String diagnosisRes = HttpFlask.sendPostFlask(FlaskDiagnosisConstants.Diagnosis_URL, postParam);
            if (!"".equals(diagnosisRes)) {
                JSONObject diagnosisJsonObject = JSONObject.parseObject(diagnosisRes);
                JSONArray json = (JSONArray) diagnosisJsonObject.get("data");
                if (json.size() > 1) {
                    for (Object o : json) {
                        JSONObject j = JSONObject.parseObject(o.toString());
                        BearingDiagnosisResult b = new BearingDiagnosisResult();
                        b.setName((String) j.get("name"));
                        b.setValue((String) j.get("value"));
                        bearingDiagnosisRes.add(b);
                    }
                } else {
                    BearingDiagnosisResult bearingDiagnosisResult = new BearingDiagnosisResult();
                    bearingDiagnosisResult.setName("error");
                    bearingDiagnosisResult.setValue("fileError");
                    bearingDiagnosisRes.add(bearingDiagnosisResult);
                }
                return bearingDiagnosisRes;
            }
        }
        return null;
    }

    /**
     * 下载在线诊断结果
     */
    public void download(HttpServletResponse response, BearingModel bearingModel) {
        try {
            String res = HttpFlask.sendGetFlask(FlaskDiagnosisConstants.Diagnosis_RESULTURL);
            if (!"".equals(res)) {
                JSONObject jsonObject = JSONObject.parseObject(res);
                String dir = (String) jsonObject.get("data");
                ServletOutputStream outputStream = response.getOutputStream();
                BufferedReader reader = new BufferedReader(new FileReader(dir + "//result.csv"));
                String line;
                while ((line = reader.readLine()) != null) {
                    outputStream.write(line.getBytes(StandardCharsets.UTF_8));
                    outputStream.write('\n');
                }
                reader.close();
                outputStream.close();
            } else {
                throw new FlaskException();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
